﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace RFW.Silverlight.Weather
{
	public partial class WindDirection : UserControl
	{
		public static readonly DependencyProperty DirectionProperty = DependencyProperty.Register("Direction", typeof(int), typeof(WindDirection), new PropertyMetadata(new PropertyChangedCallback(onDirectionChanged)));
		public static readonly DependencyProperty SpeedProperty = DependencyProperty.Register("Speed", typeof(double), typeof(WindDirection), new PropertyMetadata(new PropertyChangedCallback(onSpeedChanged)));

		public WindDirection()
		{
			InitializeComponent();
		}

		private void Canvas_SizeChanged(object sender, SizeChangedEventArgs e)
		{

		}

		public int Direction
		{
			get { return (int)this.GetValue(DirectionProperty); }
			set 
			{
				this.SetValue(DirectionProperty, value);
				pgAngle.Angle = this.Direction;

				if (this.Direction < -360)
					txtDirection.Text = "---";
				else
					txtDirection.Text = this.Direction.ToString();
			}
		}

		public double Speed
		{
			get { return (double)this.GetValue(SpeedProperty); }
			set
			{
				this.SetValue(SpeedProperty, value);

				if (this.Speed < 0)
					txtSpeed.Text = "---";
				else
					txtSpeed.Text = this.Speed.ToString();
			}
		}

		private static void onDirectionChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
		{
			if (((int)source.GetValue(e.Property)) > 360 || ((int)source.GetValue(e.Property)) < -360)
				source.SetValue(e.Property, -361);
		}

		private static void onSpeedChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
		{
			if (((double)source.GetValue(e.Property)) > 999 || ((double)source.GetValue(e.Property)) < 0)
				source.SetValue(e.Property, -1);
		}

		private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
		{
			elForeground.Width = e.NewSize.Width;
			elForeground.Height = e.NewSize.Height;

			elBackground.Width = e.NewSize.Width - 40;
			elBackground.Height = e.NewSize.Height - 40;

			double centerX = e.NewSize.Width / 2.0;
			double centerY = e.NewSize.Height / 2.0;

			elCenter.Center = new Point(centerX - 20, centerY - 20);
			pgDirection.Points = new PointCollection() { new Point(centerX, 0), new Point(centerX - 5, centerY - 5), new Point(centerX + 5, centerY - 5), new Point(centerX, 0) };
			pgAngle.CenterX = centerX;
			pgAngle.CenterY = centerY;
		}
	}
}
